#region Copyright
/// <copyright>
/// Copyright (c) 2007 Ilia Shramko.
/// Released under the terms of the GNU General Public License.
/// </copyright>
#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using Osh.Dvb;
using Osh.Configuration;

namespace Osh.Teletext
{
	public class TeletextParser : StreamParser<ITeletextStreamSource>
	{
		private TeletextService _service;

		public TeletextParser()
		{
			_service = new TeletextService(new Charset((byte)Config.Current.Osh.Teletext.DefaultLanguage));
			_service.MagazineAdd += new EventHandler<TeletextEventArgs>(TeletextService_MagazineAdd);
		}

		protected override Stream OpenStream(ITeletextStreamSource streamSource)
		{
			return streamSource.OpenTeletextStream();
		}

		protected override void ParseStream(Stream stream)
		{
			_service.Clear();
			TeletextPesReader reader = new TeletextPesReader(stream, _service);

			IPacketStream packetStream = (IPacketStream)stream;
			while(packetStream.MoveToNextPacket() && !this.StopEvent.WaitOne(0, false))
			{
				try
				{
					reader.ReadTeletextPackets();
				}
				catch(Exception e)
				{
					OnParsingError(e);
				}
			}
		}

		private static void TeletextService_MagazineAdd(object sender, TeletextEventArgs e)
		{
			e.Magazine.PageLoaded += new EventHandler<TeletextEventArgs>(TeletextMagazine_PageLoaded);
		}

		private static void TeletextMagazine_PageLoaded(object sender, TeletextEventArgs e)
		{
			Log.Info(Config.Current.TeletextTraceSource,
				"Page loaded: Mag={0}, Page={1:X}, PTS={2}",
				e.Magazine.Number, e.Page.Header.PageAddress.PageNumber, e.Page.PresentationTime);
		}

		public TeletextService TeletextService
		{
			get { return _service; }
		}
	}
}
